package com.study.meng.bigevent.controller;

import com.study.meng.bigevent.common.utils.ThreadLocalUtil;
import com.study.meng.bigevent.entity.Category;
import com.study.meng.bigevent.entity.Result;
import com.study.meng.bigevent.service.CateGoryService;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CateGoryController {
    @Resource
    private CateGoryService cateGoryService;

    /**
     * Add a new category
     */
    @PostMapping
    public Result addCategory(@RequestBody @Validated Category category) {
        Integer userId = ThreadLocalUtil.getCurrentUser();
        category.setCreateUser(userId);
        // Logic to add a category
        boolean flag = cateGoryService.add(category);
        return flag ? Result.success() : Result.error(401, "添加失败！");
    }
    /**
     * List all categories
     */
    @GetMapping
    public Result<List<Category>> list() {
        // Logic to get all categories
        return Result.success(cateGoryService.list());
    }

    @GetMapping("/detail")
    public Result<Category> detail(@RequestParam("id") Integer id) {
        // Logic to get category details by ID
        Category category = cateGoryService.detail(id);
        return category != null ? Result.success(category) : Result.error(404, "分类不存在");
    }

    /**
     * Update a category
     */
    @PutMapping
    public Result updateCategory(@RequestBody @Validated(Category.update.class) Category category) {
        // Logic to update a category
        boolean flag = cateGoryService.update(category);
        return flag ? Result.success() : Result.error(401, "修改失败！");
    }
    @DeleteMapping
    public Result deleteCategory(@RequestParam("id") Integer id) {
        // Logic to delete a category
        boolean flag = cateGoryService.delete(id);
        return flag ? Result.success() : Result.error(401, "删除失败！文章分类不存在或分类下有文章，不能删除！");
    }
}
